/*  This file is part of Phantom Power.
 *  Copyright (C) 2010 Jacob Dawid
 *
 *  Phantom Power is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Phantom Power is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Phantom Power. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef CONNECTION_H
#define CONNECTION_H

#include <QtNetwork>
#include <QObject>
#include <QTimer>
#include <QList>
#include <QMutex>
#include <QSettings>

class connection : public QObject
{
	// As the name suggests, this class handles the connection related affairs. The important point here is,
	// that it does not process the incoming data. It rather boils down all incoming data to a tiny list
	// of six or more elements and passes it to the parent class in packages of one issue at a time.

	Q_OBJECT
	public:
		connection();
		~connection();

		// Establishes a connection via TCP/IP.
		bool start(int ip1, int ip2, int ip3, int ip4, int port);
		// Stops the current connection disregarding of what type.
		bool stop();
		// Returns the connection state.
		bool connectionState();

		enum type
		{
			wifi,
			usb
		};

	private:
		connection::type thisType;
		QList<double> decodeIssue(QString issue);
		void setConnectionState(bool value);
	
		QTcpSocket* socket;
		QMutex* connectionStateMutex;
		bool _connectionState;
		QSettings* settings;
		
	public slots:
		void hostFoundSlot();
		void connectedSlot();
		void errorSlot(QAbstractSocket::SocketError socketError); 
		void disconnectedSlot();
		void readSlot();
		void synchronize();
	
	signals:
		// Will be sent out whenever an issue is available.
		void issueAvailable(QList<double> issue);
		// Will be sent out whenever there is something to report.
		void report(QString message);
		// Will be sent out whenever a control signal arrived
		void controlSignal(QString value);
};

#endif
